#!/usr/bin/env node
require("nodelib2");
require("./model");
if (__system_cmd)
{
	return;
}
var inquirer = require("inquirer");
var __scriptpath = function (...arg)
{
	return g.path.join.apply(g.path.join, [__dirname, ...arg]);
}
var conf = require(__scriptpath("./conf-default.json"));
if (g.fs.existsSync(__scriptpath("./.env.json")))
{
	conf = __merge(conf, require(__scriptpath("./.env.json")), true);
}
g.data.conf = conf;

var _scriptList = [];
var _scriptHash = {};
global.__script = null;

start();
async function start()
{
//	trace(__argv)
	var fileName = __argv.name;
	if (__argv.options.conf)
	{
		var confPathObj = g.path.parse(__argv.options.conf + "");
		if (!confPathObj.ext)
		{
			confPathObj.ext = ".json";
		}
		if (confPathObj.name.indexOf("conf-") < 0)
		{
			confPathObj.name = "conf-" + confPathObj.name;
		}
		__argv.options.conf = confPathObj.dir + "/" + confPathObj.name + confPathObj.ext;
		//留一个从其他目录发起配置和脚本
		try
		{
			g.data.conf = require(_path(__argv.options.conf));
		}
		catch (e)
		{
			console.log(e)
		}
	}
	if (!g.fs.existsSync(_bin(fileName)))
	{
		__argv.param.unshift(fileName);
		fileName = "";
	}

	if (!fileName)
	{
		var selected = await showScripList();
//		console.ansi.earseLines(2);
//		console.ansi.eraseStartLine()
		selected = selected.value;
		__script = _scriptHash[selected];
		__argv.name = __script.name;
	}
	else
	{
		__script = getScriptInfo(_bin(fileName));
	}

	for (var paramItem of __script.param)
	{
		if (paramItem.length != 3)
		{
			var answer = await inquirer.prompt([{
				type: "input",
				name: "value",
				message: `Please input ${paramItem[0]} - ${paramItem[1]}:`,
				validate: v=>!!v
			}])
			paramItem.push(isNum(answer.value) ? Number(answer.value) : answer.value);
		}
	}
//	trace(__script)
	await require(__script.path)(...__script.param.map(v=>v[v.length - 1]));
	__exit();
}

//exit();
async function showScripList()
{
	var selectOption = {
		type: "list",
		name: "value",
		message: "Select a Script File",
		choices: []
	};

	var scriptList = g.file.getDirectoryAllListing(_bin());
	scriptList = scriptList.filter(v=>
	{
		let pathObj = g.path.parse(v);
		return pathObj.ext == ".js" && pathObj.name.substr(0, 4) == "bin_";
	}).map((v, i)=>getScriptInfo(v, i + 1).show);
	selectOption.choices = scriptList.concat();
	return await inquirer.prompt(selectOption);
}

function getScriptInfo($path, $index)
{
	var scriptObj = {
		path: $path, //文件路径
		name: $path.replace(_bin() + "/", "").replace(".js", ""), //文件名
		show: "", //最终显示的完整描述
		desc: "", //描述
		param: [],
		options: __argv.options
	}

	var fileContent = g.fs.readFileSync($path).toString();
	fileContent = fileContent.substring(fileContent.indexOf("/**") + 3, fileContent.indexOf("*/"));
	fileContent.split("\n").map(v=>trim(v.replace(/\*/g, ""))).filter(v=>!!v).forEach((v, i)=>
	{
		if (i > 0)
		{
			if (v.indexOf("@param") == 0)
			{
				scriptObj.param.push(v.replace("@param ", "").split(" - "));
			}
			else if (v.indexOf("@") < 0 && !scriptObj.desc)
			{
				scriptObj.desc = v;
			}
		}
	})

	for (var i = 0; i < __argv.param.length; i++)
	{
		scriptObj.param[i] && scriptObj.param[i].push(__argv.param[i]);
	}

	var lastSplitIndex = scriptObj.name.lastIndexOf("/") + 1;
	var showName = scriptObj.name.substr(0, lastSplitIndex) + scriptObj.name.substr(lastSplitIndex + 4);
	scriptObj.show = $index + ". " + showName + " - " + scriptObj.desc;
	if (scriptObj.param.length > 0)
	{
		scriptObj.show += " {" + scriptObj.param.map(v=>v[0]).join(", ") + "}";
	}
	_scriptHash[scriptObj.show] = scriptObj;
	return scriptObj;
}

//exit();